// const WXAPI = require('apifm-wxapi')
// const wxpay = require('../../utils/pay.js')
// const AUTH = require('../../utils/auth')
var app = getApp();

Page({
  data: {
    coupon:{},
    chooseCoupon:{},
    payType: 'wxpay',
    shop_id: 0
  },
  onLoad: function (options) {
    // this.payBillDiscounts()

    var that = this;
    var shop_id = options.id;
    // var shop_id = 2;

    this.setData({
      'shop_id': shop_id
    })
    if(wx.getStorageSync('sessionkey')!=''){
      console.log("sessionkey !=null " );
      that.getCoupon();
    } else{
      console.log("sessionkey ==null " );
      app.login(isSuccess => {
        console.log("index onLoad callback isSuccess: " + isSuccess);
        if (isSuccess) {
          this.getCoupon();
        } else{
          wx.setStorageSync('isBackToMaidan', 1);
          wx.setStorageSync('shopId', shop_id);
        }
      });
    }
  },
  getCoupon: function () {
    var that = this;

    wx.request({
      url: app.d.hostUrl + '/api/user/getShopCouponInfo',
      method: 'post',
      data: {
        'shop_id': that.data.shop_id,
        'sessionkey': wx.getStorageSync('sessionkey')
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        var errmsg = res.data.msg;
        var state = res.data.code;
        if (state == 200){
          that.setData({
            coupon: res.data.data
          })
        } else {
          wx.showToast({
            title: errmsg,
            icon:"none",
            duration: 2000,
          });
        }
      },
      error: function (e) {
        wx.showToast({
          title: '网络异常',
          icon:"none",
          duration: 2000,
        });
      },
    });
  },
  createOrder: function () {
    var that = this; 
    //创建订单
    wx.request({
      url: app.d.hostUrl + '/api/shoporder/createOrder',
      method: 'post',
      data: {
        'shop_id': that.data.shop_id,
        'sessionkey': wx.getStorageSync('sessionkey'),
        'money': that.data.amount,
        'coupon_code': that.data.chooseCoupon.coupon_code,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        var errmsg = res.data.msg;
        var order_no = res.data.data.order_no;
        console.log(order_no)
        if (res.data.code == 200){
          //发起支付
          wx.request({
            url: app.d.hostUrl + '/api/payments/index',
            method: 'post',
            data: {
              'order_no': order_no,
              'sessionkey': wx.getStorageSync('sessionkey')
            },
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res);
              var errmsg = res.data.msg;
              var state = res.data.code;
              if (state == 200){
                var payd = res.data.data;
                var reobj = JSON.parse(payd);
                console.log(payd);
                console.log(reobj);
                var timeStamp1 = reobj.timeStamp;
                var nonceStr1 = reobj.nonceStr;
                var package1 = reobj.package;
                var signType1 = reobj.signType;
                var paySign1 = reobj.paySign;
                wx.requestPayment({
                  timeStamp: timeStamp1,
                  nonceStr: nonceStr1,
                  package: package1,
                  signType: signType1,
                  paySign: paySign1,
                  success (res) {
                    console.log(res);
                    wx.redirectTo({
                      url: '/pages/users/users'
                    })
                  },
                  fail (res) { }
                })
              } else {
                wx.showToast({
                  title: errmsg,
                  icon:"none",
                  duration: 2000,
                });
              }
            },
            error: function (e) {
              wx.showToast({
                title: '网络异常',
                icon:"none",
                duration: 2000,
              });
            },
          });

        } else {
          wx.showToast({
            title: errmsg,
            icon:"none",
            duration: 2000,
          });
        }
      },
      error: function (e) {
        wx.showToast({
          title: '网络异常',
          icon:"none",
          duration: 2000,
        });
      },
    });
  },
  onShow () {


  },
  async payBillDiscounts() {
    const res = await WXAPI.payBillDiscounts()
    if (res.code === 0) {
      this.setData({
        rechargeSendRules: res.data
      })
    }
  },

  async bindSave() {
    const amount = this.data.amount;
    if (!amount) {
      wx.showToast({
        title: '请填写正确的消费金额',
        icon: 'none'
      })
      return
    }
    
    if(this.data.coupon.coupon_code != '' && this.data.chooseCoupon.coupon_code == null){
      wx.showToast({
        title: '请选择优惠券',
        icon:"none",
        duration: 2000,
      });
      return;
    }
    // if ()
    // const _msg = `您本次消费${amount}，优惠后只需支付${amountReal}`
    const _msg = `您本次消费${amount}`

    wx.showModal({
      title: '请确认消费金额',
      content: _msg,
      confirmText: "确认支付",
      cancelText: "取消支付",
      success: res => {
        if (res.confirm) {
          this.createOrder()
        }
      }
    });
  },
  async goPay(amount, wxpayAmount){
    if (this.data.payType == 'balance') {
      const res = await WXAPI.payBillV2({
        token: wx.getStorageSync('token'),
        money: amount,
        pwd: this.data.pwd
      })
      if (res.code != 0) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        return
      }
      wx.showModal({
        title: '成功',
        content: '买单成功，欢迎下次光临！',
        showCancel: false
      })
    } else {
      // wxpay.wxpay('paybill', wxpayAmount, 0, "/pages/asset/index", { money: amount});
    }
  },
  payTypeChange(event) {
    this.setData({
      payType: event.detail,
    });
  },
  payTypeClick(event) {
    const { name } = event.currentTarget.dataset;
    this.setData({
      payType: name,
    });
  },
  chooseConpon: function () {
    this.setData({
      chooseCoupon: this.data.coupon,
    });
    this.hideConpon();
  },
  //显示优惠券弹出框
  showConpon: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideConpon: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
})